package com.zh.blog.security.component;

import cn.hutool.json.JSONUtil;
import com.zh.blog.common.api.Result;
import com.zh.blog.dao.UserAuthDao;
import com.zh.blog.dto.UserInfoDto;
import com.zh.blog.model.UserAuth;
import com.zh.blog.security.component.UserUtils;
import com.zh.blog.util.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.zh.blog.constant.CommonConst.APPLICATION_JSON;

/**
 * 登录成功处理类
 * @author ZhengHao
 * Created At 2022/7/29.
 **/
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Autowired
    private UserAuthDao userAuthDao;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 返回登录信息
        UserInfoDto userInfoDto = BeanCopyUtils.copyObject(UserUtils.getLoginUser(), UserInfoDto.class);
        response.setContentType(APPLICATION_JSON);
        response.getWriter().write(JSONUtil.toJsonStr(Result.ok(userInfoDto)));

        //更新用户ip，最近登录时间信息
        updateUserInfo();
    }

    /**
     * 更新用户信息
     */
    @Async
    public void updateUserInfo(){
        UserAuth userAuth = UserAuth.builder()
                .id(UserUtils.getLoginUser().getId())
                .ipAddress(UserUtils.getLoginUser().getIpAddress())
                .ipSource(UserUtils.getLoginUser().getIpSource())
                .lastLoginTime(UserUtils.getLoginUser().getLastLoginTime())
                .build();
        userAuthDao.updateById(userAuth);

    }
}